import time

import numpy as np
from scipy.interpolate import griddata, Rbf
import matplotlib.pyplot as plt
from xray_scan_collection_fft import RectangleData
from scipy.interpolate import Rbf

class XRayReconstruct:
    def __init__(self):
        # 1. 确定矩形区域和网格
        N = 111
        self.all_num = N
        a = (N-1) / 2
        #这里是指出插值区间
        self.x_min, self.x_max = -1 * a, a
        self.y_min, self.y_max = -1 * a, a
        #这里说明要插入多少个点
        self.Nx, self.Ny = N, N
        self.x = np.linspace(self.x_min, self.x_max, self.Nx)
        self.y = np.linspace(self.y_min, self.y_max, self.Ny)
        self.X, self.Y = np.meshgrid(self.x, self.y)

# 2. 数据准备  这部分待会直接输入数据
# num_points = 100
# points_x = np.random.uniform(x_min, x_max, num_points)
# points_y = np.random.uniform(y_min, y_max, num_points)
# values = np.random.rand(num_points) + 1j * np.random.rand(num_points)

    def get_all_num(self):
        return self.all_num

    def RBF_interpolation(self, rectangle_data):
        pointList = rectangle_data.get_points()

        points_x = []
        points_y = []
        values = []
        zero_value = 0
        for point in pointList:
            #处理0和-0
            if np.abs(point[0]) == 0 and np.abs(point[1]) == 0:
                zero_value += point[2]
            else:
                points_x.append(point[0])
                points_y.append(point[1])
                values.append(point[2])
        # points_x.append(0)
        # points_y.append(0)
        # values.append(zero_value)
        values = np.array(values, dtype=complex)

        # 4. 插值实现 (线性插值)
        interpolated_values = griddata(
            points=np.stack((points_x, points_y), axis=-1),
            values=values,
            xi=np.stack((self.X.flatten(), self.Y.flatten()), axis=-1),
            method='cubic',  # 修改为线性插值
            fill_value=0
        )
        interpolated_values_rbf = interpolated_values.reshape(self.X.shape)

        print(interpolated_values_rbf)

        # time.sleep(500)
        return interpolated_values_rbf

    def RBF_plot(self,interpolated_values_rbf):

        # 绘制径向基函数插值结果
        plt.figure(figsize=(5, 5))
        plt.imshow(np.abs(interpolated_values_rbf), extent=[self.x_min, self.x_max, self.y_min, self.y_max], origin='lower', cmap='viridis')
        plt.colorbar(label='Magnitude of Interpolated Values')
        plt.title('Interpolated Data')
        plt.xlabel('X')
        plt.ylabel('Y')
        plt.tight_layout()
        plt.show()